#webserver routines

import BaseHTTPServer
import sys
from datetime import datetime
import urlparse
import threading

class server(BaseHTTPServer.HTTPServer):
	stats = {}
	update_stats = None
	secret = "/home/fritz/max-secret-key"

class handler(BaseHTTPServer.BaseHTTPRequestHandler):
	secret_key = ""

	def do_GET(self):
		parsed_path = urlparse.urlparse(self.path)

		# get the secret key
		sfile = open(self.server.secret, 'r')
		self.secret_key = sfile.readline()
		self.secret_key = self.secret_key.rstrip('\n')
		sfile.close()

		if self.path.endswith(".png"):
			f = open("images" + self.path, 'rb')
			self.send_response(200)
			self.send_header("Content-type", "image/png")
			self.end_headers()
			self.wfile.write(f.read())
			f.close()
			return

		if parsed_path.path != "/" and parsed_path.path != "/" + self.secret_key:
			self.send_error(404, "File not found")
			return

		self.send_response(200)
		self.send_header("Content-type", "text/html")
		self.end_headers()
		try:
			stdout = sys.stdout #redirect stdout to client
			sys.stdout = self.wfile
			if parsed_path.path == "/":
				self.root()
			elif parsed_path.path == "/" + self.secret_key:
				self.update(parsed_path.query)
		finally:
			sys.stdout = stdout

	def root(self):
		stats = self.server.stats
		epoch = stats["epoch"]
		now = datetime.now()
	        diff = now - epoch
	        age = ':'.join(str(diff).split(':')[:2])
		

		print """
			<html>
			<head><title>HERBERT MAXIMUS FRITZ</title></head>
			<body>
			<table border=0>
			<tr><td colspan=2>HERBERT MAXIMUS FRITZ</td><tr>
			<tr><td>Current age</td><td>""" + age + """</td></tr>
			<tr><td colspan=2><hr></td></tr>
			<tr><td>Totals</td><td>Total needs: """ + stats["total_all_needs"] + """</td></tr>
			<tr><td colspan=2><hr></td></tr>
			<tr><td><center><img src="max-feedings.png"><br>Feedings</center></td><td>Last feeding: """ + stats["last_feeding"] + """</td></tr>
			<tr><td colspan=2><hr></td></tr>
			<tr><td><center><img src="max-wet.png"><br>Wet diapers</center></td><td>Last wet diaper: """ + stats["last_wet"] + """</td></tr>
			<tr><td colspan=2><hr></td></tr>
			<tr><td><center><img src="max-poopy.png"><br>Poopy diapers</center></td><td>Last poopy diaper: """ + stats["last_poopy"] + """</td></tr>
			<tr><td colspan=2><hr></td></tr>
			<tr><td><center><img src="max-unknown.png"><br>Unknown needs</center></td><td>Last unknown need: """ + stats["last_unknown"] + """</td></tr>
			<tr><td colspan=2><hr></td></tr>
			</table>
			</body>
			</html>
		"""
	
	def update(self,query):
		if query == "feeding":
			print "got feeding"
			self.server.stats = self.server.update_stats("feedings")
		elif query == "wet":
			print "got wet"
			self.server.stats = self.server.update_stats("wet")
		elif query == "poopy":
			print "got poop"
			self.server.stats = self.server.update_stats("poopy")
		elif query == "unknown":
			print "got unknown"
			self.server.stats = self.server.update_stats("unknown")
		else:
			print """
				<html>
				<head><title>update needs</title>
				<body>
				<table border=0>
				<tr><td><a href=""" + "\"" + self.secret_key + """?feeding"><img src="max-feedings.png"></a></td><td>Feeding</td></tr>
				<tr><td><a href=""" + "\"" + self.secret_key + """?wet"><img src="max-wet.png"></a></td><td>Wet</td></tr>
				<tr><td><a href=""" + "\"" + self.secret_key + """?poopy"><img src="max-poopy.png"></a></td><td>Poopy</td></tr>
				<tr><td><a href=""" + "\"" + self.secret_key + """?unknown"><img src="max-unknown.png"></a></td><td>Unknown</td></tr>
				</table>
				</body>
				</html>
			"""

def run(stats, update):
	PORT = 80
	s = server(('',PORT),handler)
	s.stats = stats
	s.update_stats = update
	s.serve_forever()

